package com.jackey.sms.utils;

import com.jackey.sms.pojo.Permission;
import com.jackey.sms.pojo.Role;
import com.jackey.sms.pojo.User;
import com.jackey.sms.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 小伟
 * @version V1.0
 * @Package com.jackey.sms.utils
 * @date 2020/12/20 14:05
 * @Copyright © 2020-2021 郑州恒星科技有限责任公司
 * 自定义用户安全数据
 */
public class CustomRealm extends AuthorizingRealm {
    @Override
    public void setName(String name) {
        super.setName("customRealm");
    }

    @Autowired
    UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户
        User user =(User) principalCollection.getPrimaryPrincipal();
        //添加用户角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        Set<String> perms = new HashSet<>();
        for (Role role : user.getRoles()) {
            roles.add(role.getName());
            for (Permission permission : role.getPermissions()) {
                perms.add(permission.getCode());
            }
        }
        info.addRoles(roles);
        info.addStringPermissions(perms);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //转换token类型
        UsernamePasswordToken upToken =(UsernamePasswordToken) authenticationToken;
        //获取用户名密码
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());
        //调用业务层验证登录密码
        User user = userService.login(username, password);
        if (user!=null) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
            return info;
        }
        return null;
    }
}
